<?php


namespace app\system\controller\cms;

use app\common\model\cms\FieldModel;
use app\system\controller\BaseController;

class FieldController extends BaseController
{

  /**
   * 不检测权限方法
   * @var array
   */
  protected $noCheck = [];

  /**
   * 权限映射
   * @var array
   */
  protected $mapCheck = [
      '*' => 'index',
  ];

  /**
   * 当前模型
   * @var null
   */
  protected $model = null;

  /**
   * 初始化
   */
  public function __construct()
  {
    parent::__construct();
    $this->model = new FieldModel();
  }

  /**
   * 添加字段
   * @return string
   * @throws \Exception
   */
  public function add()
  {
    if ($this->request->isAjax()) {
      $data = $this->request->param();
      $this->validate($data, [
          'table_name|模型表名' => 'require',
          'label_name|标签名' => 'require',
          'field_name|字段名' => 'require|alphaDash',
          'field_type|字段类型' => 'require',
          'obj_type|控件类型' => 'require',
      ]);
      $data['obj_options'] = $this->request->param('obj_options', '', null);
      $this->model->add($data);
      $this->success('操作成功');
    }
    $tableName = $this->request->param('table_name/s');
    $this->assign('table_name', $tableName);
    $this->assign('field_types', $this->model->getFieldTypes());
    $this->assign('obj_types', $this->model->getObjTypes());
    return $this->fetch();
  }

  /**
   * 修改字段
   * @return string
   * @throws \Exception
   */
  public function edit()
  {
    if ($this->request->isAjax()) {
      $data = $this->request->param();
      $this->validate($data, [
          'label_name|标签名' => 'require',
          'obj_type|控件类型' => 'require'
      ]);
      $data['obj_options'] = $this->request->param('obj_options', '', null);
      $this->model->edit($data);
      $this->success('操作成功');
    }
    $id   = $this->request->param('id/d');
    $info = $this->model->where('id', $id)->find();
    $this->assign('field_types', $this->model->getFieldTypes());
    $this->assign('obj_types', $this->model->getObjTypes());
    $this->assign('info', $info);
    return $this->fetch();
  }

  /**
   * 删除字段
   * @throws \Exception
   */
  public function del()
  {
    $id = $this->request->param('id/d');
    $this->model->del($id);
    $this->success('操作成功');
  }

  /**
   * editable
   * @return string
   */
  public function editable()
  {
    try {
      $data = $this->request->param();
      $this->validate($data, [
          'pk|标识' => 'number',
          'name|键' => 'require',
          'value|值' => 'require',
      ]);
      $this->model->where('id', $data['pk'])->update([$data['name'] => $data['value']]);
    } catch (\Throwable $th) {
      return response($th->getMessage(), 500);
    }
    return 'ok';
  }
}